#include "input.h"
#include <iostream>
#include <memory>
#include "tower.h"
#include "game.h"
#include "button.h"

using namespace std;

CInput::CInput() {
    gameover = false;
}

void CInput::Init() {
    gamescene->SetRegistryValue("pointer_state", PSTATE_HOVER);
    gamescene->btn()->push_back(std::unique_ptr<CButton>(new CButton(800,150,224,50,"pointer_state",PSTATE_PLACEMENT_TOWER,gamescene)));
}

CInput::~CInput() {

}

int CInput::GetMouseX() {
    return mouse_x;
}

int CInput::GetMouseY() {
    return mouse_y;
}

void CInput::update() {    
    while(SDL_PollEvent(&event))
    if (event.type == SDL_MOUSEMOTION) {
        mouse_x = event.motion.x;
        mouse_y = event.motion.y;
    } else if (event.type == SDL_MOUSEBUTTONDOWN) {        
        if (gamescene->GetRegistryValue("pointer_state") == PSTATE_PLACEMENT_TOWER && mouse_x <= 800) {
            bool ok = true;
            for (auto it = gamescene->obj()->begin(); it != gamescene->obj()->end(); it++) {
                int minx = (*it)->GetX() - (*it)->GetW()/2;
                int miny = (*it)->GetY() - (*it)->GetH()/2;
                int maxx = (*it)->GetX() + (*it)->GetW()/2;
                int maxy = (*it)->GetY() + (*it)->GetH()/2;
                if (mouse_x >= minx && mouse_x <= maxx && mouse_y >= miny && mouse_y <= maxy) {
                    ok = false;
                }
            }
            if (ok && gamescene->GetCredits() >= 5) {
                gamescene->obj()->push_back(std::unique_ptr<CObject>(new CTower(mouse_x,mouse_y,gamescene)));
                gamescene->Credit(-5);
            }
        }
        for (auto it = gamescene->btn()->begin(); it != gamescene->btn()->end(); it++) {
            if ((*it)->Detect(mouse_x,mouse_y)) {
                (*it)->Push();
            }
        }
        for (auto it = gamescene->obj()->begin(); it != gamescene->obj()->end(); it++) {
            int minx = (*it)->GetX() - (*it)->GetW()/2;
            int miny = (*it)->GetY() - (*it)->GetH()/2;
            int maxx = (*it)->GetX() + (*it)->GetW()/2;
            int maxy = (*it)->GetY() + (*it)->GetH()/2;

            if (mouse_x >= minx && mouse_x <= maxx && mouse_y >= miny && mouse_y <= maxy) {
                gamescene->SetRegistryValue("pointer_state", PSTATE_SELECTED);
                selected = (*it).get();
            }

        }
    } else if (event.type == SDL_KEYDOWN) {
        if (event.key.keysym.sym == SDLK_ESCAPE) {
            gamescene->setGameOver();
        }
    } else if (event.type == SDL_QUIT) {
        gamescene->setGameOver();
    }
}

void CInput::assignScene(CScene *scene) {
    gamescene = scene;
    Init();
}

int CInput::GetState() {
    return gamescene->GetRegistryValue("pointer_state");
}

CObject* CInput::GetSelected() {
    return selected;
}

